package com.carrie.service.impl;

import com.carrie.mapper.BagsWithGoodsMapper;
import com.carrie.model.Bag;
import com.carrie.model.Goods;
import com.carrie.service.BagWithGoodsService;
import com.carrie.tools.LogUtils;
import com.carrie.tools.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author XuHaiLong
 * @since 2025/4/14 00:43
 */
@Service
public class BagWithGoodsServerImpl implements BagWithGoodsService {
    @Value("${UPLOAD_DIR}")
    private  String UPLOAD_DIR;// 文件服务器的物理存储路径
    @Autowired
    private BagsWithGoodsMapper bagsWithGoodsMapper;

    @Override
    public List<Bag> getAllBageWithGoods() {
        return bagsWithGoodsMapper.getAllBagsWithGoods();
    }

    @Override
    public Result insertBag(int bagId, String bagIcon, String bagName) {
        System.out.println(bagId);
        System.out.println(bagIcon);
        System.out.println(bagName);
        if (bagId > 0 && bagIcon != null && bagName != null) {
            bagsWithGoodsMapper.insertBag(bagId, bagIcon, bagName);
            return new Result(200, "success");
        } else {
            return new Result(400, "参数不合法");
        }
    }
    @Override
    public Result insertGoodsIntoBag(int bagId, MultipartFile file, Goods goods) {
        LogUtils.info("进入 insertGoodsIntoBag 方法，bagId: {}", bagId); // 新增日志
        if (!file.isEmpty()) {
            try {
                // 创建上传目录
                File uploadDir = new File(UPLOAD_DIR);
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    if (!created) {
                        // 处理目录创建失败的情况
                        throw new IOException("无法创建上传目录: " + UPLOAD_DIR);
                    }
                }

                // 生成唯一的文件名
                String originalFilename = file.getOriginalFilename();
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
                String newFilename = timestamp + "_" + originalFilename;
                Path path = Paths.get(UPLOAD_DIR + File.separator + newFilename);

                // 将文件写入指定路径
                byte[] bytes = file.getBytes();
                Files.write(path, bytes);

                // 返回文件的访问 URL
                String fileUrl = "/imgs/" + newFilename;
                goods.setImage(fileUrl);
            }catch (IOException e) {
                LogUtils.error("上传失败:>>>>"+e.getMessage());
                return new Result(1010,"上传失败");
            }try {
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                System.out.println("bagId:"+bagId);
                System.out.println(goods.getImage());
                System.out.println(goods.getAmount());
                System.out.println(goods.getDesc());
                System.out.println(goods.getName());
                System.out.println(goods.getSummary());
                System.out.println(goods.getLevel());
                System.out.println("<<<<<<<<<<<<<<<<<<<<<<<");
                bagsWithGoodsMapper.insertGoodsIntoBag(bagId, goods);
                return Result.success("ok");
            } catch (AccessDeniedException e) {
                throw new AccessDeniedException("你无权限操作");
            } catch (Exception e) {
                return new Result(500, "内部服务器错误，请联系管理员");
            }
        }else {
            return new  Result(2001,"文件未上传");
        }
    }

}
